<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import {
  ElButton
  // ElTag,
  // ElMessageBox
} from 'element-plus'

import { Table } from '@/components/Table'

import { zcMarkOrderEditApi } from '@/api/cy/xMarking'
// import { zcReleaseOrderListApi, adminFaPastureEditApi } from '@/api/fa/pasture'

import { useTable } from '@/hooks/web/useTableTest'
import {
  // h,
  ref,
  unref,
  reactive
} from 'vue'

import Add from './components/Add.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
// 获取字典
import { useCache } from '@/hooks/web/useCache'
import { sysDictRelsApi } from '@/api/dict'

import city from './components/city'
import { spMarketPriceAddAdminApi, spMarketPriceListApi } from '@/api/cy/EverydayPrice'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')

// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

const dictRelsData = ref() // 联动数据
const searchRef = ref() // 搜索的标签
const cityData: any = ref() //城市枚举
const breedSubData: any = ref([]) // 品种的枚举

// 获取联动关系
const getDictRels = async () => {
  const res = await sysDictRelsApi({
    p_type: 'breed',
    c_type: 'breed_sub'
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    dictRelsData.value = res.data
  }
}

const provinceChange = (value) => {
  cityData.value = city[value]
  // console.log(value, city[value], 'value')
  const new_search = unref(searchRef)
  new_search.setData({ ...new_search.getData(), city: '' })
}

const Province = (value) => {
  let data = city.area.find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

const City = (a, value) => {
  let num = Number(a.province)

  let data = city[num].find((item) => {
    return item.value == value
  })
  // console.log(a, value, data, 'data')
  return data ? data.label : ''
}
// 选择畜别的时候触发，处理品种类容
const breedChange = (value) => {
  breedGetSub(value)
  const new_search = unref(searchRef)
  new_search.setData({ ...new_search.getData(), breed_sub: '' })
}

// 根据畜别查询品种
const breedGetSub = async (breed_value) => {
  // console.log('breed_value', breed_value, !breed_value)
  if (!breed_value) {
    breedSubData.value = []
  } else {
    let breedData = dictRelsData.value.find((item) => {
      return item.value == breed_value
    })
    breedSubData.value = breedData.children
  }
}

const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: spMarketPriceListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { getList, setSearchParams } = methods

// getList()

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '主键',
    fixed: 'left',
    width: 60,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },

  {
    field: 'province',
    label: '省',
    width: 200,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return Province(cellValue)
    },
    search: {
      label: '110100',
      component: 'Select',
      componentProps: {
        options: city.area,
        onChange: provinceChange
      },
      show: true
    }
  },
  {
    field: 'city',
    label: '市',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return City(_, cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: cityData
      },
      show: true
    }
  },
  {
    field: 'breed',
    label: '畜别',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed', cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.breed,
        onChange: breedChange
      },
      show: true
    }
  },
  {
    field: 'breed_sub',
    label: '品种',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed_sub', cellValue)
    },
    width: 150,
    search: {
      component: 'Select',
      componentProps: {
        options: breedSubData
      },
      show: true
    }
  },
  {
    field: 'price',
    label: '今日价格',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'create_user_name',
    label: '创建人',
    width: 150,
    search: {
      show: false
    }
  },
  // {
  //   field: 'state',
  //   label: '状态',
  //   width: 150,
  //   formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
  //     return getDictLabel('mark_state', cellValue)
  //   },
  //   search: {
  //     component: 'Select',
  //     componentProps: {
  //       options: dict.insurance_order_state
  //     },
  //     show: true
  //   }
  // },
  {
    field: 'time',
    label: '发布时间',
    width: 200,
    form: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        disabled: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    search: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        'is-range': true,
        'unlink-panels': true,
        rangeSeparator: 'To',
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    }
  },
  {
    field: 'create_time',
    label: '创建时间',
    width: 200,
    form: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        disabled: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    search: {
      show: false,
      component: 'DatePicker',
      componentProps: {
        'is-range': true,
        'unlink-panels': true,
        rangeSeparator: 'To',
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    }
  },
  {
    field: 'note',
    label: '备注',
    width: 150,
    search: {
      show: false
    }
  }
  // {
  //   field: 'action',
  //   width: 120,
  //   fixed: 'right',
  //   label: t('tableDemo.action'),
  //   form: {
  //     show: false
  //   },
  //   detail: {
  //     show: false
  //   }
  // }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

const actionType = ref('')

const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      dialogTitle.value = '编辑'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'add':
      dialogTitle.value = '新增'
      tableObject.currentRow = {
        is_stop: '0'
      }
      // tableObject.currentRow = row
      dialogVisible.value = true
      break
    default:
      console.log('未知类型')
  }
}

const editRef = ref()
const loading = ref(false)
const save = async () => {
  // console.log(unref(editRef), 'l')
  const edit = unref(editRef)
  switch (actionType.value) {
    case 'edit':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await edit?.getFormData()) as any
          console.log(3333, data)
          let res = await zcMarkOrderEditApi({
            id: data.id,
            pasture_org_id: data.pasture_org_id,
            pasture_dept_id: data.pasture_dept_id,
            number: data.number,
            breed: data.breed,
            breed_sub: data.breed_sub,
            purpose: data.purpose,
            freight: Number(data.freight)
          })
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      console.log(await edit.getFormData(), '111')
      break
    case 'add':
      await edit?.ruleFormRef.validate(async (valid) => {
        if (valid) {
          let res = await spMarketPriceAddAdminApi({
            my_dept_id: wsCache.get('userInfo').default_dept_id,
            breed: edit.ff.breed,
            breed_sub: edit.ff.breed_sub,
            province: edit.ff.selectedOptions[0].padEnd(6, '0'),
            city: edit.ff.selectedOptions[1].padEnd(6, '0'),
            time: edit.ff.time,
            note: edit.ff.note,
            price: edit.ff.price
          })
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          console.log(res, 'add')
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }

          console.log(edit.ff, 'ff')
        }
      })
      break
    default:
      console.log('未知类型')
  }
}

const init = async () => {
  // 列表查询
  await getList()
  // 获取关联关系
  await getDictRels()
}
init()
</script>

<template>
  <ContentWrap>
    <!-- <div style="text-align: center; margin: 20px 0; font-weight: 900; font-size: 50px">
      111.00
    </div> -->
    <Search
      ref="searchRef"
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
    />
    <div class="mb-10px">
      <ElButton type="primary" @click="action('add')">新增</ElButton>
    </div>
    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
      :selection="false"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Add
      v-if="actionType == 'add'"
      ref="editRef"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    />

    <template #footer>
      <ElButton
        v-if="actionType !== 'see' && actionType !== 'add'"
        type="primary"
        :loading="loading"
        @click="save()"
      >
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton v-if="actionType == 'add'" type="primary" :loading="loading" @click="save()">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
